"""The voice_assistant_contro integration."""
from __future__ import annotations

import logging
from typing import Any

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant

from .const import (
    DOMAIN,
    CONF_ENTITIES,
    TUNNEL_SERVER_URL
)


from .command_handler import CommandHandler
from .websocket_client import VoiceAssistantWebSocket
# from .tunnel_client import TunnelClient
from .tcp_tunnel_client import TCPTunnelClient

_LOGGER = logging.getLogger(__name__)
PLATFORMS = ["sensor"]

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up voice_assistant_contro from a config entry."""
    # 获取实体列表（优先从选项获取，否则从数据获取）
    entities = entry.options.get(CONF_ENTITIES, entry.data.get(CONF_ENTITIES, []))
    
    # 创建命令处理器
    command_handler = CommandHandler(
        hass=hass,
        entities=entities,
        send_message_callback=None,  # 稍后设置
        auth_state_callback=None,  # 稍后由传感器设置
    )
    
    # 创建 websocket 客户端
    websocket = VoiceAssistantWebSocket(
        hass=hass,
        entry=entry,
        message_handler=command_handler.handle_message,
        connection_state_callback=None  # 稍后由传感器设置
    )
    
    # 创建TCP隧道客户端
    tunnel_client = TCPTunnelClient(
        hass=hass,
        entry=entry,
        server_url=TUNNEL_SERVER_URL,
        connection_state_callback=None  # 稍后由传感器设置
    )
    
    # 设置命令处理器的消息发送回调
    command_handler._send_message = websocket.send_message

    # 存储实例
    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
        "websocket": websocket,
        "command_handler": command_handler,
        "tunnel_client": tunnel_client,
    }
    _LOGGER.info("实例已存储")
    # 设置平台
    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
    
    # 启动 websocket 和隧道客户端
    _LOGGER.info("正在连接 WebSocket 和 TCP Tunnel...")
    await websocket.connect()
    _LOGGER.info("WebSocket 连接成功")
    await tunnel_client.connect()
    _LOGGER.info("TCP Tunnel 连接成功")
    # 注册停止回调
    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, websocket.disconnect)
    )

    # 注册配置选项更新监听器
    async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
        """当配置选项更新时重新加载集成。"""
        await hass.config_entries.async_reload(entry.entry_id)

    entry.async_on_unload(
        entry.add_update_listener(async_update_options)
    )

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    # 卸载平台
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        data = hass.data[DOMAIN].pop(entry.entry_id, None)
        if data:
            await data["websocket"].disconnect()
            await data["tunnel_client"].disconnect()
            
    return unload_ok 